package com.smallkingson.ylib.view;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.HorizontalScrollView;
import android.widget.RelativeLayout;
import android.widget.Scroller;

import com.smallkingson.ylib.core.Yr;
import com.smallkingson.ylib.view.callback.YPositionOnClickListener;
import com.smallkingson.ylib.view.utils.YViews;

public class YHorizontalView extends HorizontalScrollView {

	private static final int ID_HEAD = 10000;
	List<View> views;
	private Context context;
	private RelativeLayout relativeLayout;
	private int indicatorHeight = 5;
	private int indicatorColor = Color.RED;
	private int currentIndicatorTrans;
	private int currentIndicatorWidth;
	private View indicator;
	Scroller scroller;
	private int duration = 500;
	private boolean indicatorMoving;
	private int selectedIndex;
	private boolean isPaddingToMargin = true;

	private OnItemClickedListener onItemClickedListener;
	private boolean reLayout;

	public YHorizontalView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

		this.context = context;

		views = new ArrayList<View>();
		scroller = new Scroller(context, new AnticipateOvershootInterpolator());

	}

	public YHorizontalView(Context context) {
		this(context, null, 0);
	}

	public YHorizontalView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public YHorizontalView add(View tv) {

		if (views.contains(tv)) {
			return this;
		}
		views.add(tv);

		return this;
	}

	public void clear() {
		this.removeAllViews();
		if (relativeLayout != null) {
			relativeLayout.removeAllViews();
		}
		views.clear();
	}

	@SuppressLint("NewApi")
	public void ok() {

		setup();
	}

	@SuppressLint("NewApi")
	private void setup() {
		this.removeAllViews();

		if (relativeLayout != null) {
			relativeLayout.removeAllViews();
		}

		relativeLayout = new RelativeLayout(context);

		this.addView(relativeLayout);

		YViews.setViewWH(relativeLayout, LayoutParams.WRAP_CONTENT,
				LayoutParams.MATCH_PARENT);

		for (int i = 0; i < views.size(); i++) {

			View view = views.get(i);

			view.setId(ID_HEAD + i);

			relativeLayout.addView(view);

			RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
					.getLayoutParams();

			// 高度填充满
			layoutParams.height = LayoutParams.MATCH_PARENT;

			// 设置居中
			layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);

			if (i > 0) {
				// 下一个textview 处于上一个textview的右边
				layoutParams.addRule(RelativeLayout.RIGHT_OF, ID_HEAD + i - 1);
			}

			view.setLayoutParams(layoutParams);

			// 给子类用
			onTextViewAdded(relativeLayout, view, ID_HEAD + i);

			// 设置点击事件
			view.setOnClickListener(new YPositionOnClickListener(i) {

				@Override
				public void onClick(View v) {

					if (this.position == selectedIndex) {

						if (onItemClickedListener != null) {
							onItemClickedListener.onItemClicked(
									views.get(selectedIndex), selectedIndex,
									false);
						}
						return;
					}
					setItem(this.position);
				}
			});
		}

		// 最有一个view的marginRight不起作用 用这个代替
		relativeLayout.setPadding(0, 0, ((RelativeLayout.LayoutParams) views
				.get(views.size() - 1).getLayoutParams()).rightMargin, 0);

		// 初始化 第一个indicator

		indicator = new View(context);

		relativeLayout.addView(indicator);
		// 放在底部 并且对齐第一个textview
		RelativeLayout.LayoutParams indicatorLayoutParams = (RelativeLayout.LayoutParams) indicator
				.getLayoutParams();

		indicatorLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

		indicator.setLayoutParams(indicatorLayoutParams);

		currentIndicatorTrans = ((RelativeLayout.LayoutParams) views.get(0)
				.getLayoutParams()).leftMargin;

		indicator.setTranslationX(currentIndicatorTrans);
		// 设置背景颜色
		indicator.setBackgroundColor(indicatorColor);

		currentIndicatorWidth = getIndicatorWidth(0, this.views);

		YViews.setViewWH(indicator, currentIndicatorWidth, indicatorHeight);
		// 设置首个textview选中

		setItem(0);
	}

	public void setIndicatorVisibility(int Visibility) {
		indicator.setVisibility(Visibility);
	}

	protected int getIndicatorWidth(int i, List<View> views) {
		return YViews.getViewWidth(views.get(i));
	}

	/**
	 * 
	 * @param view
	 * @param i
	 */
	protected void onTextViewAdded(RelativeLayout relativeLayout, View view,
			int i) {

	}

	@SuppressLint("NewApi")
	@Override
	public void computeScroll() {

		if (indicatorMoving) {
			if (scroller.computeScrollOffset()) {

				// 这里调用View的scrollTo()完成实际的滚动
				// scrollTo(scroller.getCurrX(), 0);

				int currX = scroller.getCurrX();
				int currY = scroller.getCurrY();
				indicator.setTranslationX(currX);
				YViews.setViewWidth(indicator, currY);
				// 必须调用该方法，否则不一定能看到滚动效果
				currentIndicatorTrans = currX;
				currentIndicatorWidth = currY;
				postInvalidate();
			} else {
				indicatorMoving = false;
			}
		}
		super.computeScroll();
	}

	// 移动指示条
	protected void moveIndicator(final int tagetTextViewX,
			final int tagetTextViewWidth) {

		indicatorMoving = true;

		scroller.startScroll(currentIndicatorTrans, currentIndicatorWidth,
				tagetTextViewX - currentIndicatorTrans, tagetTextViewWidth
						- currentIndicatorWidth, duration);
		postInvalidate();
	}

	public YHorizontalView setIndicatorHeight(int indicatorHeight) {
		this.indicatorHeight = indicatorHeight;
		return this;
	}

	public YHorizontalView setIndicatorColor(int indicatorColor) {
		this.indicatorColor = indicatorColor;
		return this;
	}

	public boolean isPaddingToMargin() {
		return isPaddingToMargin;
	}

	public void setPaddingToMargin(boolean isPaddingToMargin) {
		this.isPaddingToMargin = isPaddingToMargin;
	}

	public YHorizontalView setDuration(int duration) {
		this.duration = duration;
		return this;
	}

	public YHorizontalView setOnItemClickedListener(
			OnItemClickedListener onItemClickedListener) {
		this.onItemClickedListener = onItemClickedListener;
		return this;
	}

	public static interface OnItemClickedListener {

		void onItemClicked(View selectedView, int index, boolean isChanged);
	}

	public void setItem(int index) {
		setItem(index, true);
	}

	public void setItem(int index, boolean isSendListener) {

		selectedIndex = index;

		View view = views.get(index);
		// 设置选中
		for (View v : views) {

			YViews.setAllViewsSelected(v, false);
		}
		view.setSelected(true);

		// 找出该控件左边距离

		View selectedView = views.get(index);
		int viewX = getViewX(index, views, selectedView);

		Yr.d(viewX);
		// 移动scrollView
		YHorizontalView.this.smoothScrollTo(
				viewX - YHorizontalView.this.getWidth() / 2
						+ selectedView.getMeasuredWidth() / 2, 0);
		if (selectedView.getWidth() == 0) {

			YViews.addOnceOnGlobalLayoutListener(selectedView,
					new YViews.ParamsDoSomeThing(viewX, selectedView, isSendListener) {

						@Override
						public void doSomeThing(View v, Object[] params) {
							int viewX = (Integer) params[0];
							View selectedView = (View) params[1];
							boolean isSendListener = (Boolean) params[2];
							// 移动indicator
							moveIndicator(viewX, getNextWidth(selectedView));

							// 通知观察者
							if (isSendListener) {
								if (onItemClickedListener != null) {
									onItemClickedListener.onItemClicked(
											views.get(selectedIndex),
											selectedIndex, true);
								}
							}
						}

					});
		} else {
			// 移动indicator
			moveIndicator(viewX, getNextWidth(selectedView));
			// 通知观察者
			if (isSendListener) {
				if (onItemClickedListener != null) {
					onItemClickedListener.onItemClicked(
							views.get(selectedIndex), selectedIndex, true);
				}
			}
		}
	}

	/**
	 * 重写该方法 可以控制指示器在滑动的时候想要的长度
	 * 
	 * @param selectedView
	 * @return
	 */
	protected int getNextWidth(View selectedView) {
		return selectedView.getMeasuredWidth();
	}

	protected int getViewX(int index, List<View> views, View selectedView) {

		int viewX = 0;
		for (int j = 0; j < index; j++) {
			View v = views.get(j);
			RelativeLayout.LayoutParams lp = ((RelativeLayout.LayoutParams) v
					.getLayoutParams());
			viewX += v.getWidth();
			viewX = viewX + lp.leftMargin + lp.rightMargin;
		}
		viewX += ((RelativeLayout.LayoutParams) selectedView.getLayoutParams()).leftMargin;

		Yr.d(selectedView.getMeasuredWidth());

		int intw = MeasureSpec.makeMeasureSpec(0,
				MeasureSpec.UNSPECIFIED);
		int inth = MeasureSpec.makeMeasureSpec(0,
				MeasureSpec.UNSPECIFIED);
		selectedView.measure(intw, inth);
		int intwidth = selectedView.getMeasuredWidth();
		Yr.d(intwidth);
		viewX += (intwidth - getNextWidth(selectedView)) / 2;
		return viewX;
	}

	public void attach(final ViewPager vp) { 
 
		if (vp == null) {
			return;
		}

		setOnItemClickedListener(new OnItemClickedListener() {

			@Override
			public void onItemClicked(View selectedView, int index,
					boolean isChanged) {
				vp.setCurrentItem(index);
			}
		});

		vp.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int page) {
				setItem(page, false);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

	}

}
